package com.example05.demo.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

public class MybatisUtils {

    private static SqlSessionFactory factory = null;
    private static final String resource = "mybatis-config.xml";
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    static {
        try {
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            Reader resourceAsReader = Resources.getResourceAsReader(resource);
            factory = sqlSessionFactoryBuilder.build(resourceAsReader);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public static SqlSessionFactory getSqlSessionFactory(){
        return factory;
    }
    public static SqlSession getSqlSession(Boolean isAutoCommit){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null){
            sqlSession = factory.openSession(isAutoCommit);
        }
        return sqlSession;
    }
    public static SqlSession getSqlSession(){
        return getSqlSession(true);
    }
    public static <T> T getMapper(Class<T> clazz){
        return getSqlSession().getMapper(clazz);
    }
}
